package com.note.web;

import com.note.common.core.controller.BaseController;
import com.note.common.core.domain.AjaxResult;
import com.note.common.core.domain.entity.SysUser;
import com.note.common.core.domain.model.LoginUser;
import com.note.common.utils.ServletUtils;
import com.note.common.utils.StringUtils;
import com.note.common.utils.uuid.IdUtils;
import com.note.domain.BaiduyunInfo;
import com.note.domain.SourceLiking;
import com.note.domain.SourceScreenshots;
import com.note.dto.BaiduYunInfoResponse;
import com.note.dto.BaiduyunInfoDTO;
import com.note.framework.web.service.TokenService;
import com.note.request.SourceSearchRequest;
import com.note.service.IBaiduyunInfoService;
import com.note.system.service.ISysUserService;
import com.note.util.FileProxyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2021-04-16
 */
@Api("百度云")
@Controller
@RequestMapping("/baiduYun")
public class BaiduyunInfoController extends BaseController
{
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    IBaiduyunInfoService baiduyunInfoService;

    @Autowired
    private TokenService tokenService;

    /**
     * 将用户变为vip或者取消vip
     */
    @ResponseBody
    @ApiOperation("将用户变为vip或者取消vip")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userId",value="用户id",dataType="long", paramType = "query"),
            @ApiImplicitParam(name="vip",value="0:非vip 1:vip",dataType="int", paramType = "query")})
    @GetMapping("/updateVip")
    public boolean updateVip(Long  userId, int vip)
    {
        try {
            sysUserService.updateVip(userId, vip);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }







    /**
     * 保存学习资源
     */
    @ResponseBody
    @ApiOperation("保存学习资源")
    @PostMapping("/saveSource")
    public AjaxResult saveSource(BaiduyunInfoDTO baiduyunInfo, List<MultipartFile> screenshots)
    {
        try {
            baiduyunInfo.setScreenshotList(screenshots);
            baiduyunInfoService.insertBaiduyunInfo(baiduyunInfo);
            return AjaxResult.success("保存资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success("保存资源异常");

        }
    }







    /**
     * 搜索资源
     */
    @ResponseBody
    @ApiOperation("搜索资源")
    @GetMapping("/searchSource")
    public AjaxResult  searchSource(SourceSearchRequest sourceSearchRequest)
    {
        try {
            startPage();
            List<BaiduYunInfoResponse>  baiduyunInfoList = baiduyunInfoService.searchSourceList(sourceSearchRequest);
            FileProxyUtil.setProxyPrefix(baiduyunInfoList, BaiduyunInfo::getCoverUrl, (baiduyunInfo, url) -> {
                baiduyunInfo.setCoverUrl(url);
                return baiduyunInfo;
            });
            return AjaxResult.success(getDataTable(baiduyunInfoList));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("搜索资源异常");
        }

    }

    private BaiduYunInfoResponse getDetail(String  sourceId){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = null;
        if(loginUser != null){
            userId = loginUser.getUser().getUserId();
        }
        BaiduYunInfoResponse baiduYunInfoResponse = baiduyunInfoService.searchASourceDetail(sourceId, userId);
        BaiduyunInfo preSource = baiduyunInfoService.preOrNextSource(1, baiduYunInfoResponse.getClassification(), baiduYunInfoResponse.getId(), baiduYunInfoResponse.getCreateTime());
        BaiduyunInfo nextSource = baiduyunInfoService.preOrNextSource(2, baiduYunInfoResponse.getClassification(), baiduYunInfoResponse.getId(), baiduYunInfoResponse.getCreateTime());
        baiduYunInfoResponse.setPreSource(preSource);
        baiduYunInfoResponse.setNextSource(nextSource);
        FileProxyUtil.setProxyPrefix(baiduYunInfoResponse, BaiduyunInfo::getCoverUrl, (baiduyunInfo, url) -> {
            baiduyunInfo.setCoverUrl(url);
            return baiduyunInfo;
        });
        FileProxyUtil.setProxyPrefix(baiduYunInfoResponse.getScreenshotImgList(), SourceScreenshots::getScreenshotUrl, (sourceScreenshots, url) -> {
            sourceScreenshots.setScreenshotUrl(url);
            return sourceScreenshots;
        });
        return baiduYunInfoResponse;
    }

    /**
     * 获取资源详情,后台获取，返回资源的密码和链接
     */
    @ResponseBody
    @ApiOperation("获取资源详情-后台")
    @GetMapping("/detailSourceBack")
    public AjaxResult  detailSourceBack(String  sourceId)
    {
        if(StringUtils.isEmpty(sourceId)){
            return AjaxResult.error("资源id 为空");
        }
        try {
            BaiduYunInfoResponse detail = getDetail(sourceId);
            return AjaxResult.success(detail);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取详情异常");
        }

    }



    /**
     * 获取资源详情,前台获取，不返回资源的密码和链接
     */
    @ResponseBody
    @ApiOperation("获取资源详情-前台")
    @GetMapping("/detailSourceFront")
    public AjaxResult  detailSourceFront(String  sourceId)
    {
        if(StringUtils.isEmpty(sourceId)){
            return AjaxResult.error("资源id 为空");
        }
        try {
            BaiduYunInfoResponse detail = getDetail(sourceId);
            if("0".equals(detail.getFree())){
                //清空资源的密码和链接
                detail.setSourcePwd("");
                detail.setSourceUrl("");
            }

            return AjaxResult.success(detail);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取详情异常");
        }

    }



    /**
     * 编辑资源详情
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name="screenshotFile",value="有新增截图时，把file传过来"),
            @ApiImplicitParam(name="coverFile",value="换封面时，把file传过来")})
    @ResponseBody
    @ApiOperation("编辑资源详情")
    @PostMapping("/editSource")
    public AjaxResult  editSource(BaiduyunInfoDTO baiduyunInfoDTO, MultipartFile[] screenshotFile, MultipartFile coverFile)
    {
        if(StringUtils.isEmpty(baiduyunInfoDTO.getId())){
            return AjaxResult.error("资源id为空");
        }

        String coverUrl = FileProxyUtil.removeProxyPerfix(baiduyunInfoDTO.getCoverUrl());
        baiduyunInfoDTO.setCoverUrl(coverUrl);


        baiduyunInfoDTO.setScreenshotList(Arrays.asList(screenshotFile));
        baiduyunInfoDTO.setCover(coverFile);
        try {
            baiduyunInfoService.editSource(baiduyunInfoDTO);
            return AjaxResult.success("更新资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新资源异常");
        }

    }





    /**
     * 删除资源
     */
    @ResponseBody
    @ApiOperation("删除资源")
    @DeleteMapping("/deleteSource")
    public AjaxResult  deleteSource(String[] sourceIds)
    {
        try {
            baiduyunInfoService.deleteSource(Arrays.asList(sourceIds));
            return AjaxResult.success("删除资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("删除资源异常");
        }

    }



    /**
     * 根据用户的密钥，获取到对应资源的链接和提取码
     */
    @ResponseBody
    @ApiOperation("根据用户的密钥，获取到对应资源的链接和提取码")
    @GetMapping("/getSourceUrlAndPwdByKey")
    public AjaxResult  getSourceUrlAndPwdByKey(String  sourceIdKey, String sourceId)
    {
        if(StringUtils.isEmpty(sourceIdKey)){
            return AjaxResult.error("sourceIdKey 为空");
        }

        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            SysUser user = loginUser.getUser();
            SysUser sysUser = sysUserService.selectUserById(user.getUserId());
            if(!sourceIdKey.equals(sysUser.getSourceKey())){
                return AjaxResult.error("密钥不对");
            }
            BaiduYunInfoResponse detail = getDetail(sourceId);
            return AjaxResult.success(detail);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取详情异常");
        }

    }


    /**
     * 获取轮播的资源，默认返回6张
     * @param sourceId 点击详情时的资源id，由此获取同类的，然后返回
     * @return
     */
    @ResponseBody
    @ApiOperation("获取轮播的资源列表")
    @GetMapping("/getShufflingSourceList")
    public AjaxResult  getShufflingSourceList(String sourceId)
    {
        if(StringUtils.isEmpty(sourceId)){
            return AjaxResult.error("sourceId 为空");
        }

        try {
            List<BaiduyunInfo> shufflingSourceList = baiduyunInfoService.getShufflingSourceList(sourceId);
            FileProxyUtil.setProxyPrefix(shufflingSourceList, BaiduyunInfo::getCoverUrl, (baiduyunInfo, url) -> {
                baiduyunInfo.setCoverUrl(url);
                return baiduyunInfo;
            });
            return AjaxResult.success(shufflingSourceList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取轮播图异常");
        }

    }


    @ResponseBody
    @ApiOperation("点赞")
    @GetMapping("/liking")
    public AjaxResult liking(String sourceId){
        if(StringUtils.isEmpty(sourceId)){
            return AjaxResult.error("资源id为空");
        }

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        SourceLiking sourceLiking = new SourceLiking();
        sourceLiking.setId(IdUtils.randomUUID());
        sourceLiking.setCreateUser(user.getUserId());
        sourceLiking.setCreateDate(new Date());
        sourceLiking.setSourceId(sourceId);

        baiduyunInfoService.liking(sourceLiking);

        return AjaxResult.success("点赞成功");
    }


    /**
     *
     * @param num 需要返回的个数
     * @return
     */
    @ResponseBody
    @ApiOperation("获取点赞最多的列表")
    @GetMapping("/getMaxLikeSourceList")
    public AjaxResult getMaxLikeSourceList(Integer num){


        try {
            List<BaiduyunInfo> maxLikeSourceList = baiduyunInfoService.getMaxLikeSourceList(num);
            FileProxyUtil.setProxyPrefix(maxLikeSourceList, BaiduyunInfo::getCoverUrl, (baiduyunInfo, url) -> {
                baiduyunInfo.setCoverUrl(url);
                return baiduyunInfo;
            });
            return AjaxResult.success(maxLikeSourceList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取点赞最多的列表异常");
        }


    }



}
